<template>
  <div class="form-single-fragment" style="position: relative">
    <router-header :title="item_title"></router-header>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="140px"
      size="mini"
      label-position="right"
    >
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="20">
          <div class="title"><h4>基本信息</h4></div>
          <el-row>
            <el-form-item label="项目关联" style="padding: 20px 0">
              <el-button @click="queryByContract()">关联合同</el-button>
              <el-button @click="queryByBusinessOpportunity('1')"
                >关联商机</el-button
              >
              <el-button @click="queryByClue">关联线索</el-button>
            </el-form-item>

            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectName">
                <el-input
                  class="input-item"
                  v-model="ruleForm.projectName"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="ruleForm.projectCode">
              <el-form-item label="合同编号" prop="projectCode">
                <el-input
                  class="input-item"
                  placeholder="请输入"
                  :value="ruleForm.projectCode"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业名称" prop="customerName">
                <el-input
                  class="input-item"
                  v-model="ruleForm.customerName"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业联系人" prop="contacts">
                <el-input
                  class="input-item"
                  v-model="ruleForm.contacts"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业联系人电话" prop="telephone">
                <el-input
                  class="input-item"
                  v-model="ruleForm.telephone"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计合同金额" prop="estimatedAmount">
                <el-input
                  type="number"
                  class="input-item"
                  v-model="ruleForm.estimatedAmount"
                  placeholder="请输入"
                >
                  <el-select v-model="ruleForm.units" slot="append" placeholder="请选择" style="width: 130px; padding: 0px 20px; margin: -5px -50px;">
                    <el-option
                      v-for="item in unitsList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label">
                    </el-option>
                  </el-select>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计成交日期" prop="estimatedDate">
                <el-date-picker
                  v-model="ruleForm.estimatedDate"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <!--   <el-col :span="12">
              <el-form-item label="单位名称" prop="customerId">
                <el-select v-model="ruleForm.customerId" filterable placeholder="请选择">
                  <el-option v-for="(item,index) in customerlist" :key="index"
                    :label="item.custName" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <!--    <el-col :span="12">
              <el-form-item label="项目开始时间" prop="beginDate">
                <el-date-picker v-model="ruleForm.beginDate" type="date" placeholder="选择日期"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目完成时间" prop="endDate">
                <el-date-picker v-model="ruleForm.endDate" type="date" placeholder="选择日期"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="所在地区" prop="areaId">
                <el-cascader
                  v-model="ruleForm.areaId"
                  ref="ref_areaCodes"
                  :options="areaCodelist"
                  :props="areaCodeprops"
                  :show-all-levels="true"
                  clearable
                  @change="areaCodesChange"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="业务类型" prop="businessType">
                <el-cascader
                  v-model="ruleForm.businessType"
                  ref="ref_business"
                  :options="businesstypeTree"
                  :props="businesstProps"
                  :show-all-levels="false"
                  clearable
                  @change="businessChange"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="监督部门">
                <el-input class="input-item" v-model="ruleForm.superviseDept" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审批部门">
                <el-input class="input-item" v-model="ruleForm.approvalDept" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目总投资(万元)">
                <el-input class="filter-item" v-model="ruleForm.projectTotalAmount" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程投资">
                <el-input class="input-item" v-model="ruleForm.projectInvestmentAmount" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="行业" prop="hyType">
                <el-select
                  v-model="ruleForm.hyType"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) in industryList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="项目属性" prop="projectAttribute">
                <el-select v-model="ruleForm.projectAttribute" placeholder="请选择">
                  <el-option label="公司项目" :value="1"></el-option>
                  <el-option label="合作单位" :value="2" v-if="(cooperateFlag==1&&stageFlag==0)||(cooperateFlag==1&&stageFlag==1)"></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item
                label="合作单位"
                prop="cooperateCompany"
                v-if="
                  ruleForm.projectAttribute == 2 &&
                  cooperateFlag == 1 &&
                  stageFlag == 1
                "
              >
                <el-select
                  v-model="ruleForm.cooperateCompany"
                  placeholder="请选择"
                >
                  <el-option label="物产公司" :value="1"></el-option>
                  <el-option label="刘玲群" :value="2"></el-option>
                  <el-option label="其他单位" :value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="项目标段"
                prop="stageNumber"
                v-if="businessCode == 'ZB'"
              >
                <el-select
                  ref="selectStage"
                  v-model="ruleForm.stageNumber"
                  @change="selectStageNumber"
                  placeholder="请选择"
                >
                  <el-option label="标段一" :value="1"></el-option>
                  <el-option label="标段二" :value="2"></el-option>
                  <el-option label="标段三" :value="3"></el-option>
                  <el-option label="标段四" :value="4"></el-option>
                  <el-option label="标段五" :value="5"></el-option>
                  <el-option label="标段六" :value="6"></el-option>
                  <el-option label="标段七" :value="7"></el-option>
                  <el-option label="标段八" :value="8"></el-option>
                  <el-option label="标段九" :value="9"></el-option>
                  <el-option label="标段十" :value="10"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="采购方式"
                prop="procurement"
                v-if="businessCode == 'ZB'"
              >
              <!-- @change="selectProcurementMode" -->
                <el-select
                  ref="selectProcurement"
                  v-model="ruleForm.procurement"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in procurementList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="投标项目" prop="isTobid">
                <el-radio-group v-model="ruleForm.isTobid">
                  <el-radio :label="0">否</el-radio>
                  <el-radio :label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="保密协议" prop="isBm">
                <el-radio-group v-model="ruleForm.isBm">
                  <el-radio :label="0">否</el-radio>
                  <el-radio :label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="ruleForm.isBm === 1">
              <el-form-item label="上传保密协议" prop="fileList">
                <Upload v-model="ruleForm.fileList" :limit="10" fielState="1"></Upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目简述" prop="projectDescription">
                <el-input
                  class="input-item"
                  type="textarea"
                  :autosize="{ minRows: 2 }"
                  maxlength="150"
                  show-word-limit
                  v-model="ruleForm.projectDescription"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="note">
                <el-input
                  class="input-item"
                  type="textarea"
                  :autosize="{ minRows: 2 }"
                  maxlength="150"
                  show-word-limit
                  v-model="ruleForm.note"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="title">
            <h4>项目成员</h4>
            <el-button type="primary" size="mini" @click="setPeople"
              >添加成员</el-button
            >
          </div>
          <div class="table_container">
            <el-table
              :data="ruleForm.projectUserDtoList"
              size="mini"
              style="width: 100%"
              header-cell-class-name="table-header-gray"
            >
              <el-table-column
                type="index"
                align="center"
                width="55"
                label="序号"
              ></el-table-column>
              <el-table-column
                prop="showName"
                align="center"
                label="姓名"
              >
                <template slot-scope="scope">
                  {{scope.row.showName}}
                </template>
              </el-table-column>
              <el-table-column
                prop="mobile"
                align="center"
                label="手机号"
              ></el-table-column>
              <el-table-column
                prop="leaderName"
                align="center"
                label="项目角色"
              >
                <template slot-scope="scope">
                  {{ scope.row.leaderName }}
                </template>
              </el-table-column>
              <el-table-column
                prop="deptName"
                align="center"
                label="部门"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  {{ scope.row.deptName || scope.row.deptIdDictMapname }}
                </template>
              </el-table-column>
              <el-table-column prop="postName" align="center" label="岗位">
                <template slot-scope="scope">
                  {{ scope.row.postName || scope.row.userTypeDictMapname }}
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="120">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="setPeople(scope.row)"
                    :disabled="scope.row.notSubmit"
                    >编辑</el-button
                  >
                  <!-- notSubmit -->
                  <el-button
                    type="text"
                    @click="deleteUserDtoList(scope.row, scope.$index)"
                    :disabled="scope.row.notSubmit"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-row
            v-for="(list, index) in ruleForm.projectInitiationTaskList"
            :key="index"
          >
            <div class="title">
              <h4>
                项目任务 - {{ list[0].businessTypeName }}
                {{ list[0].stageName ? " - " + list[0].stageName : '' }}
              </h4>
              <el-button type="primary" size="mini" @click="setTasks(index)"
                >添加任务</el-button
              >
            </div>
            <el-row>
              <el-table
                :data="list"
                size="mini"
                style="width: 100%"
                header-cell-class-name="table-header-gray"
                border
              >
                <el-table-column
                  type="index"
                  align="center"
                  width="50"
                  label="序号"
                >
                </el-table-column>
                <el-table-column prop="task" align="center" label="任务">
                  <template slot-scope="scope">
                    <span :class="{ require: !!scope.row.achievementFlag }">
                      {{ scope.row.task }}</span
                    >
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  prop="fileUrl"
                  align="center"
                  label="成果文件"
                ></el-table-column> -->
                <el-table-column
                  prop="examine"
                  align="center"
                  label="是否审核"
                  show-overflow-tooltip
                >
                  <template slot-scope="{ row }">
                    {{ row.examine == 1 ? '是' : '否' }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="sealIsNo"
                  align="center"
                  label="是否盖章"
                  show-overflow-tooltip
                >
                  <template slot-scope="{ row }">
                    {{ row.sealIsNo == 1 ? '是' : '否' }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="executorName"
                  align="center"
                  label="执行人"
                  show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                  prop="startTime"
                  align="center"
                  label="预计开始时间"
                ></el-table-column>
                <el-table-column
                  prop="completionTime"
                  align="center"
                  label="预计完成时间"
                ></el-table-column>
                <el-table-column label="操作" align="center" width="140">
                  <template slot-scope="scope">
                    <!-- <el-button type="text" @click="aaa(scope)">上传</el-button> -->
                    <el-button type="text" @click="getTasksupdata(scope, index)"
                      >编辑</el-button
                    >
                    <el-button type="text" @click="deleteTask(scope, index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-row>
          <el-row v-if="ruleForm.projectInitiationTaskList && ruleForm.projectInitiationTaskList.length > 0">
            <div class="title">
              <h4>项目计划</h4>
              <!-- {{ruleForm.projectInitiationTaskList}} -->
              <!-- <el-button type="primary" size="mini" @click="setPlans"
                >创建计划</el-button
              > -->
            </div>
            <div class="fullCalendarCont">
              <GanttChart
                :dataList="ruleForm.projectInitiationTaskList.flat(Infinity)"
              ></GanttChart>
              <!-- <full-calendar
              ref="calendar"
              :config="config"
              :events="events"
            ></full-calendar> -->
            </div>
          </el-row>
          <div class="title"><h4>项目审批流程</h4></div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="审批流程" style="padding: 20px 0">
                <!-- :getUserFn="$Administration.ProjectApproval" -->
                <approver
                  :approverList="ruleForm.approver"
                  :typeId="3"
                  :isEdit="!!$route.query.projectId"
                  @handleChooseapprover="handleChooseapprover"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="抄送" style="padding: 20px 0">
                <approver
                  :typeId="3"
                  :isCc="true"
                  :approverList="ruleForm.cc"
                  @handleChooseapprover="handleChooseapproverCc"
                ></approver>
                <!-- <el-select
                  v-model="ruleForm.cc"
                  multiple
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="getUserList"
                  :loading="groupLoading"
                  style="display: block"
                  class="multiple-select"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in groupList"
                    :key="item.userId"
                    :label="item.loginName"
                    :value="item.userId"
                  ></el-option>
                </el-select> -->
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-form-item style="padding: 20px 0">
        <el-button @click="resetForm()">取消</el-button>
        <el-button type="primary" @click="submitForm()">提交</el-button>
      </el-form-item>
    </el-form>
    <div class="annotation" v-if="setRolebox">
      <setRole ref="setRole" @getRole="getRole" v-model="setRolebox"></setRole>
    </div>
    <div class="annotation" v-if="selectPeoplebox">
      <selectPeople
        ref="selectPeople"
        @getPeople="getPeople"
        v-model="selectPeoplebox"
      ></selectPeople>
    </div>
    <div class="annotation" v-if="setPlanbox">
      <setPlan
        ref="setPlan"
        @getPlans="getPlans"
        @upPlans="upPlans"
        @changePlans="changePlans"
        v-model="setPlanbox"
      ></setPlan>
    </div>
    <!-- 关联合同 -->
    <el-dialog title="关联合同" :visible.sync="relationDialog1">
      <el-form
        :line="true"
        label-position="right"
        :model="relationQueryParmas1"
        label-width="80px"
      >
        <el-col :span="10">
          <el-form-item label="合同名称">
            <el-input
              v-model="relationQueryParmas1.contractName"
              placeholder="请输入内容"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="企业名称">
            <el-input
              v-model="relationQueryParmas1.enterpriseName"
              placeholder="请输入内容"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              @click="onSubmitContract"
            >搜索</el-button>
          </el-form-item>
        </el-col>
      </el-form>
      <el-table
        :data="relationList1"
        size="mini"
        style="width: 100%"
        header-cell-class-name="table-header-gray"
        v-loading="isShowloading"
        border
      >
        <el-table-column
          type="index"
          align="center"
          width="55"
          label="序号"
        ></el-table-column>
        <el-table-column
          prop="contractName"
          align="center"
          width="150"
          label="合同名称"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="contractCode"
          align="center"
          width="100"
          label="合同编码"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="enterpriseName"
          align="center"
          label="企业名称"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="regionName"
          align="center"
          label="所在地区"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="contractStatusName"
          align="center"
          label="合同状态"
          show-overflow-tooltip
        >
          <template slot-scope="{ row }">
            {{ row.verifyStatus | statusFilter }}
          </template>
        </el-table-column>

        <!-- <el-table-column prop="businessTypeName" align="center" label="业务类型" show-overflow-tooltip></el-table-column> -->
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="createUserName"
          align="center"
          label="创建人"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="220">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              @click="handleChooseRelation1(row)"
              size="mini"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" style="margin-top: 10px">
        <el-pagination
          background
          @size-change="handleRelationSizeChange1"
          @current-change="handleRelationCurrentChange1"
          :current-page="relationQueryParmas1.current"
          :page-size="relationQueryParmas1.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, prev, pager, next, sizes"
          :total="relationTotal1"
        ></el-pagination>
      </el-row>
    </el-dialog>
    <!-- 关联商机 -->
    <el-dialog title="关联商机" :visible.sync="relationDialog2">
      <el-form
        :line="true"
        label-position="right"
        :model="relationQueryParmas2"
        label-width="80px"
      >
        <el-col :span="10">
          <el-form-item label="商机名称">
            <el-input
              v-model="relationQueryParmas2.oppoName"
              placeholder="请输入内容"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="企业名称">
            <el-input
              v-model="relationQueryParmas2.custName"
              placeholder="请输入内容"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              @click="onSubmitBusiness('1')"
            >搜索</el-button>
          </el-form-item>
        </el-col>
      </el-form>
      <el-table
        :data="relationList2"
        size="mini"
        style="width: 100%"
        header-cell-class-name="table-header-gray"
        v-loading="isShowloading"
        border
      >
        <el-table-column
          type="index"
          align="center"
          width="55"
          label="序号"
        ></el-table-column>
        <el-table-column
          prop="oppoName"
          align="center"
          width="150"
          label="商机名称"
        >
        </el-table-column>
        <el-table-column
          prop="custName"
          align="center"
          label="企业名称"
          show-overflow-tooltip
        ></el-table-column>
        <!-- <el-table-column
          prop="oppoStatusName"
          align="center"
          label="商机状态"
          show-overflow-tooltip
        >
        </el-table-column> -->
        <el-table-column
          prop="regionName"
          align="center"
          label="所在地区"
          show-overflow-tooltip
        ></el-table-column>
        <!-- <el-table-column
          prop="businessTypeName"
          align="center"
          label="业务类型"
          show-overflow-tooltip
        ></el-table-column> -->
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
          width="140"
        ></el-table-column>
        <el-table-column
          prop="createUserName"
          align="center"
          label="创建人"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="contractAmount"
          align="center"
          label="预计合同额度"
          width="120"
        ></el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="220">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              @click="handleChooseRelation2(row)"
              size="mini"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" style="margin-top: 10px">
        <el-pagination
          background
          @size-change="handleRelationSizeChange2"
          @current-change="handleRelationCurrentChange2"
          :current-page="relationQueryParmas2.current"
          :page-size="relationQueryParmas2.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, prev, pager, next, sizes"
          :total="relationTotal2"
        ></el-pagination>
      </el-row>
    </el-dialog>
    <!-- 关联线索 -->
    <el-dialog title="关联线索" :visible.sync="relationDialog3">
      <el-form
        :line="true"
        label-position="right"
        :model="relationQueryParmas3"
        label-width="80px"
      >
        <el-col :span="10">
          <el-form-item label="线索名称">
            <el-input
              v-model="relationQueryParmas3.clueName"
              placeholder="请输入内容"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="企业名称">
            <el-input
              v-model="relationQueryParmas3.customerName"
              placeholder="请输入内容"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              @click="onSubmitClue"
            >搜索</el-button>
          </el-form-item>
        </el-col>
      </el-form>
      <el-table
        :data="relationList3"
        size="mini"
        style="width: 100%"
        header-cell-class-name="table-header-gray"
        v-loading="isShowloading"
      >
        <el-table-column
          type="index"
          align="center"
          width="55"
          label="序号"
        ></el-table-column>
        <el-table-column
          prop="clueName"
          align="center"
          label="线索名称"
          show-overflow-tooltip
        ></el-table-column>
        <!-- <el-table-column
          prop="businessTypeName"
          align="center"
          label="业务类型"
          show-overflow-tooltip
        ></el-table-column> -->
        <el-table-column
          prop="customerName"
          align="center"
          label="企业名称"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="regionName"
          align="center"
          label="所在地区"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="contacts"
          align="center"
          label="企业联系人"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="telephone"
          align="center"
          label="联系电话"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="clueStatus"
          align="center"
          label="线索状态"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span v-for="(item, indexs) in clueStatuslist" :key="indexs">
              {{ item.value == scope.row.clueStatus ? item.name : "" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="clueSource"
          align="center"
          label="线索来源"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="createUserName"
          align="center"
          label="创建人"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="80">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              @click="handleChooseRelation3(row)"
              size="mini"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" style="margin-top: 10px">
        <el-pagination
          background
          @size-change="handleRelationSizeChange3"
          @current-change="handleRelationCurrentChange3"
          :current-page="relationQueryParmas3.current"
          :page-size="relationQueryParmas3.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, prev, pager, next, sizes"
          :total="relationTotal3"
        ></el-pagination>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Administration, Contracts } from '@/api/projectAdministration.js';
import { BusinessOpportunities, Customers } from '@/api/commercial.js';
import { Businesstype, Tasktemplate } from '@/api/business.js';
import { OnlineDictController } from '@/api/onlineController.js';
import { EcologicalkKnowledge } from '@/api/knowledgeBases.js';
import { clone, getType} from '@/utils/index.js';
import setRole from '@/components/selector/setRole.vue';
import selectPeople from '@/components/selector/selectPeople.vue';
import setPlan from '@/components/selector/setPlan.vue';
import TasksAdd from './TasksAdd.vue';
import GanttChart from './components/GanttChart.vue';
import approver from './components/approver';
import { SystemController } from '@/api';
// import Tasks from './components/tasks.vue';
// import { FullCalendar } from 'vue-full-calendar'
import 'fullcalendar/dist/fullcalendar.css';
// import { getToken } from '@/utils';
// import { Leave } from '@/api/approve.js';
const chineseNum = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
export default {
  name: 'Projectsadd',
  components: { setRole, selectPeople, setPlan, GanttChart, approver },
  data () {
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入企业联系人电话'));
      // } else if (!/^0311-\d{7}$/.test(value)) {
      } else if (!/^(\d{1,4})-(\d{6,8})$/.test(value) && !/^1\d{10}$/.test(value)) {
        callback(new Error('企业联系人电话格式不正确'));
      } else {
        callback();
      }
    };
    return {
      unitsList: [
        {value: '0', label: '元'},
        {value: '1', label: '万元'},
        {value: '2', label: '亿元'}
      ],
      procurementList: [
        {value: '0', label: '公开招标'},
        {value: '1', label: '邀请招标'},
        {value: '2', label: '竞争性磋商'},
        {value: '3', label: '竞争性谈判'},
        {value: '4', label: '询价'},
        {value: '5', label: '单一来源'},
        {value: '6', label: '进口产品采购'},
        {value: '7', label: '比选'}
      ],
      // formContract: {
      //   ContractName: null,
      //   companyName: null
      // },
      // formBusiness: {
      //   BusinesstName: null,
      //   companyName: null
      // },
      formClue: {
        ClueName: null,
        companyName: null
      },
      urlimg: require('@/assets/img/default-header.png'),
      item_title: '项目立项',
      fristTaskId: '',
      setRolebox: false,
      selectPeoplebox: false,
      setPlanbox: false,
      loading: false,
      isShowloading: false,
      userId: null,
      areaCodelist: [],
      areaCodeprops: {
        label: 'name',
        value: 'id',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      clueStatuslist: [
        { name: '全部', value: '' },
        { name: '待立项', value: '0' },
        { name: '已完成', value: '1' },
        { name: '已终止', value: '2' }
      ],
      businessCode: '',
      stageFlag: '',
      cooperateFlag: '',
      businesstypeTree: [],
      businesstProps: {
        value: 'id',
        label: 'businessName',
        children: 'children',
        emitPath: false,
        multiple: true
      },
      customerlist: [],
      radio1: '0',
      value: new Date(),
      dropdownprops: {
        label: 'deptName',
        value: 'deptId'
      },
      industryList: '',
      tableIndex: 0,
      ruleForm: {
        areaId: '',
        beginDate: '',
        businessType: [],
        businessTypeParentIds: [],
        customerId: '',
        endDate: '',
        projectAttribute: '',
        projectName: '',
        projectCode: '',
        stageNumber: '', // 标段
        stageName: '', // 标段名称
        procurement: '', // 采购方式
        cooperateCompany: '',
        projectTotalAmount: '',
        projectInvestmentAmount: '',
        superviseDept: '',
        approvalDept: '',
        hyType: '',
        projectDescription: '',
        note: '',
        customerName: '',
        telephone: '',
        contacts: '',
        isTobid: 0,
        isState: '',
        isBm: 0,
        estimatedDate: '', // 预计合同金额
        estimatedAmount: '', // 预计成交日期
        fileList: [],
        projectPlanDtoList: [], // 项目计划列表
        projectInitiationTaskList: [], // 项目任务列表
        originalTaskList: [], // 原始任务列表
        projectUserDtoList: [], // 项目成员列表
        approver: [], // 审批流
        units: ''
      },
      rules: {
        projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        projectCode: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
        customerName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        contacts: [{ required: true, message: '请输入企业联系人', trigger: 'blur' }],
        telephone: [{ required: true, message: '请输入企业联系人电话', trigger: 'blur' }, { validator: checkPhone, trigger: 'blur' }],
        areaId: [{ required: true, message: '请选择地区', trigger: 'change' }],
        businessType: [{ required: true, message: '请选择业务类型', trigger: 'change' }],
        hyType: [{ required: true, message: '请选择行业', trigger: 'change' }],
        cooperateCompany: [{ required: true, message: '请选择合作单位', trigger: 'change' }],
        // stageNumber: [{ required: true, message: '请选择项目标段', trigger: 'change' }],
        isTobid: [{ required: true, message: '请选择是否为投标项目', trigger: 'change' }],
        isBm: [{ required: true, message: '请选择是否上传保密协议', trigger: 'change' }],
        // fileList: [{ required: true, message: '请上传保密协议', trigger: 'change' }],
        projectDescription: [{ required: false, message: '请输入项目简述', trigger: 'blur' }],
        note: [{ required: false, message: '请输入备注', trigger: 'blur' }],
        projectUserDtoList: [{ required: true, message: '请选择项目成员', trigger: 'change' }],

        customerId: [{ required: true, message: '请选择', trigger: 'change' }],
        beginDate: [{ required: true, message: '请选择', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择', trigger: 'change' }],
        projectAttribute: [{ required: true, message: '请选择', trigger: 'change' }]

      },
      config: {
        header: {
          left: 'prev,next today',
          center: 'title',
          right: 'month,agendaWeek,agendaDay,list'
        },
        buttonText: { today: '今天', month: '月', week: '周', day: '日', list: '日程' },
        locale: 'zh-cn',
        defaultView: 'month', // 显示默认视图
        // weekMode: 'liquid',
        // weekNumbers: true,
        // height: 'auto',
        timeFormat: '-', // HH:mm
        navLinks: true, // can click day/week names to navigate views
        eventLimit: 3, // 限制一天中显示的事件数，默认false
        allDayText: '排班', // 日历上显示全天的文本
        selectable: true, // 允许用户通过单击或拖动选择日历中的对象，包括天和时间。
        selectHelper: false, // 当点击或拖动选择时间时，显示默认加载的提示信息，该属性只在周/天视图里可用。
        unselectAuto: true, // 当点击页面日历以外的位置时，自动取消当前的选中状态。
        eventBackgroundColor: '#3a87ad', // 设置日程事件的背景色
        eventClick: this.eventClick
      },
      events: [],
      indexPlans: '',

      // 合同
      relationDialog1: false,
      relationList1: [],
      relationTotal1: 0,
      relationQueryParmas1: {
        size: 10,
        current: 1,
        contractName: null,
        enterpriseName: null
      },
      // 商机
      relationDialog2: false,
      relationList2: [],
      relationTotal2: 0,
      relationQueryParmas2: {
        size: 10,
        current: 1,
        // isState: 1,
        oppoName: null,
        custName: null
      },
      // 线索
      relationDialog3: false,
      relationList3: [],
      relationTotal3: 0,
      relationQueryParmas3: {
        size: 10,
        current: 1,
        clueName: null,
        customerName: null
      },
      groupList: [], // 抄送下拉选数据源
      groupLoading: false, // 抄送转圈圈
      fileList: []
    };
  },
  computed: {
    ...mapGetters([
      'getUserInfo'
    ])
  },
  filters: {
    chineseNumFilter (val) {
      const data = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
      return data[val] ? data[val] : val
    },
    leaderFlagFilter (val) {
      const data = {
        0: '负责人',
        1: '协作人',
        2: '关键因素推动人',
        3: '外资企业',
        4: '合资企业',
        5: '私营企业',
        6: '事业单位',
        7: '国家行政机关'
      };
      return data[val] ? data[val] : val;
    },
    statusFilter (val) {
      const data = {
        1: '会审审批中',
        2: '会审审批通过',
        3: '会审审批驳回',
        4: '盖章审批中',
        5: '盖章审批驳回',
        6: '审批完成',
        7: '待归档',
        8: '归档中',
        9: '归档驳回',
        10: '已完成'
      }
      return data[val]
    }
  },
  created () {
    this.fristTaskId = Number(this.getDateTime.dateTimeStr('ymdhi') + '001')
    this.loadbusinesstypeTree()
    this.loadareaCodelistDict()
    this.loadCustomerList()
    this.loadOnlineDictControllerData()
    this.addManager();
    this.ruleForm.units = this.unitsList[0].label
  },
  mounted () {
    if (this.$route.query.projectId) {
      this.item_title = '编辑项目';
      this.loadDetailWidgetData()
    }
    if (this.$route.query.oppoId) {
      this.item_title = '商机转立项';
      this.loadOpportunitiesdetail()
      this.loadContractdetail()
    }
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    getUserList (query) {
      this.groupLoading = true
      SystemController.getUserList(this, {
        orderParam: [{ asc: false, fieldName: 'loginName' }],
        pageParam: {
          pageNum: 1,
          pageSize: 100000
        },
        sysUserDtoFilter: { loginName: query }
      })
        .then((res) => {
          this.groupList = res.data.dataList;
          this.groupLoading = false
        })
        .catch((e) => {
          this.groupLoading = false
        });
    },
    // 审批人选择
    handleChooseapprover (approver) {
      console.log('我执行了吗', approver);
      this.ruleForm.approver = approver
      console.log('this.ruleForm', this.ruleForm);
    },
    // 抄送人选择
    handleChooseapproverCc (approver) {
      this.ruleForm.cc = approver
    },
    // projectUserDtoList
    // 增加负责人
    addManager () {
      console.log('getUserInfo', this.getUserInfo)
      let obj = {
        notSubmit: true,
        userId: this.getUserInfo.userId,
        showName: this.getUserInfo.showName,
        mobile: this.getUserInfo.mobile || '',
        leaderFlag: 0,
        leaderName: '负责人',
        deptName: this.getUserInfo.deptName || '',
        postName: this.getUserInfo.postName || ''
      };
      this.ruleForm.projectUserDtoList.unshift(obj);
    },
    // 选择标段
    selectStageNumber () {
      this.$nextTick(() => {
        this.ruleForm.stageName = this.$refs.selectStage.selected?.label;
        this.ruleForm.projectInitiationTaskList = Object.assign([], this.ruleForm.originalTaskList);
        let i = 0;
        this.ruleForm.originalTaskList.map((val, idx) => {
          val.map((v, j) => {
            v.stageName = '标段一';
            v.stageNumber = 1;
            return v;
          });
          let arr = [];
          if (val[0].businessTypeCode === 'ZB') {
            for (let i = 1; i < this.ruleForm.stageNumber; i++) {
              let newVal = clone(val);
              newVal = newVal.map((v, j) => {
                v.stageName = `标段${chineseNum[i]}`;
                v.stageNumber = i + 1;
                return v;
              });
              arr.push(Object.assign([], newVal));
            }
            this.ruleForm.projectInitiationTaskList.splice(i + 1, 0, ...arr);
            i += this.ruleForm.stageNumber;
            return false;
          }
          i += 1;
        });
      });
    },
    // 获取合同列表
    queryByContract () {
      this.relationDialog1 = true;
      Contracts.queryByContract(this, this.relationQueryParmas1)
        .then((res) => {
          this.relationList1 = res.data.records;
          this.relationTotal1 = res.data.total;
        })
        .catch((e) => { });
    },
    // 搜索合同列表
    onSubmitContract () {
      this.queryByContract();
    },
    // 获取商机列表
    queryByBusinessOpportunity (state) {
      let params = {
        ...this.relationQueryParmas2,
        isState: state,
        allOppo: 100
      }
      this.ruleForm.isState = state
      this.relationDialog2 = true;
      Administration.queryByBusinessOpportunity(this, params)
        .then((res) => {
          this.relationList2 = res.data.records;
          this.relationTotal2 = res.data.total;
        })
        .catch((e) => { });
    },
    // 搜索商机列表
    onSubmitBusiness (state) {
      let params = {
        ...this.relationQueryParmas2,
        isState: state,
        allOppo: 100
      }
      this.ruleForm.isState = state
      this.relationDialog2 = true;
      Administration.queryByBusinessOpportunity(this, params)
        .then((res) => {
          this.relationList2 = res.data.records;
          this.relationTotal2 = res.data.total;
        })
        .catch((e) => { });
      // this.queryByBusinessOpportunity();
    },
    // 获取线索列表
    queryByClue () {
      this.relationDialog3 = true;
      this.ruleForm.isState = 1
      Contracts.queryByClue(this, this.relationQueryParmas3)
        .then((res) => {
          this.relationList3 = res.data.records;
          this.relationTotal3 = res.data.total;
        })
        .catch((e) => { });
    },
    // 搜索线索列表
    onSubmitClue () {
      this.queryByClue();
    },
    // 关联合同中的选择按钮
    handleChooseRelation1 (row) {
      // 项目名称
      this.ruleForm.projectName = row.contractName;
      // 合同编码
      this.ruleForm.projectCode = row.contractCode;
      // 企业名称
      this.ruleForm.customerName = row.enterpriseName;
      // 企业联系人
      this.ruleForm.contacts = row.contactPerson;
      // 联系电话
      this.ruleForm.telephone = row.telephone;
      // 所在地区
      this.ruleForm.areaId = Number(row.districtCode);
      // 合同id
      this.ruleForm.contractId = row.id;

      // // 业务类型
      // this.ruleForm.businessType = row.businessType;
      // // 行业类型
      // this.ruleForm.hyType = row.detailedAddress;

      this.relationDialog1 = false;
    },
    // 关联商机中的选择按钮
    handleChooseRelation2 (row) {
      // 项目名称
      this.ruleForm.projectName = row.oppoName;
      // 合同编码
      this.ruleForm.projectCode = row.contractCode;
      // 企业名称
      this.ruleForm.customerName = row.custName;
      // 企业联系人
      this.ruleForm.contacts = row.contacts;
      // 联系电话
      this.ruleForm.telephone = row.telephone;
      // 所在地区
      this.ruleForm.areaId = Number(row.oppoDistrictCode);

      // 商机id
      this.ruleForm.businessOpportunityId = row.id;
      this.relationDialog2 = false;
    },
    // 关联线索中的选择按钮
    handleChooseRelation3 (row) {
      // 项目名称
      this.ruleForm.projectName = row.clueName;
      // 合同编码
      this.ruleForm.projectCode = row.contractCode;
      // 企业名称
      this.ruleForm.customerName = row.customerName;
      // 企业联系人
      this.ruleForm.contacts = row.contacts;
      // 联系电话
      this.ruleForm.telephone = row.telephone;
      // 所在地区
      this.ruleForm.areaId = Number(row.districtCode);

      // 线索id
      this.ruleForm.clueId = row.id;

      this.relationDialog3 = false;
    },

    // 关联合同中的选择分页size
    handleRelationSizeChange1 (val) {
      this.relationQueryParmas1.size = val;
      this.queryByContract();
    },
    // 关联合同中的选择current
    handleRelationCurrentChange1 (val) {
      this.relationQueryParmas1.current = val;
      this.queryByContract();
    },
    // 关联商机中的选择分页size
    handleRelationSizeChange2 (val) {
      this.relationQueryParmas2.size = val;
      this.queryByBusinessOpportunity(this.ruleForm.isState);
    },
    // 关联商机中的选择current
    handleRelationCurrentChange2 (val) {
      this.relationQueryParmas2.current = val;
      this.queryByBusinessOpportunity(this.ruleForm.isState);
    },
    // 关联线索中的选择分页size
    handleRelationSizeChange3 (val) {
      this.relationQueryParmas3.size = val;
      this.queryByClue();
    },
    // 关联线索中的选择current
    handleRelationCurrentChange3 (val) {
      this.relationQueryParmas3.current = val;
      this.queryByClue();
    },
    /**
     * 所属行业
     */
    loadOnlineDictControllerData () {
      let params = {
        dictId: '1475422753933758464'
      }
      return new Promise((resolve, reject) => {
        OnlineDictController.view(this, params).then(res => {
          this.industryList = JSON.parse(res.data.dictDataJson).dictData
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 商机详情
     */
    loadOpportunitiesdetail () {
      let params = this.$route.query.oppoId;
      return new Promise((resolve, reject) => {
        BusinessOpportunities.detail(this, params).then(res => {
          this.ruleForm.customerId = res.data.customerId
          this.ruleForm.areaId = Number(res.data.oppoDistrictCode)
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 合同详情
     */
    loadContractdetail () {
      let params = {
        opportunityId: this.$route.query.oppoId
      };
      return new Promise((resolve, reject) => {
        Contracts.opportunity(this, params).then(res => {
          this.ruleForm.businessType = res.data.businessType
          this.ruleForm.projectCode = res.data.contractCode
          this.ruleForm.projectAttribute = res.data.projectAttribute
          this.ruleForm.cooperateCompany = res.data.cooperateCompany
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 项目立项详情
     */
    loadDetailWidgetData () {
      let params = {
        id: this.$route.query.projectId
      };
      return new Promise((resolve, reject) => {
        Administration.detail(this, params).then(res => {
          let data = res.data.project;
          this.ruleForm = data;
          this.stageFlag = data.stageFlag
          this.cooperateFlag = data.cooperateFlag
          this.businessCode = data.businessTypeCode;
          this.ruleForm.businessType = data.businessType.split(',');
          this.ruleForm.approver = res.data?.processTask?.data;
          this.ruleForm.cc = this.ruleForm.cc.split(',')
          this.ruleForm.cc = this.ruleForm.cc.map((item, i) => {
            return {
              userId: item,
              showName: this.ruleForm.ccUserName && this.ruleForm.ccUserName[i]
            }
          })
          let filePath = data?.filePath;
          this.ruleForm.fileList = getType(filePath).isString ? JSON.parse(filePath) : filePath;
          this.ruleForm.projectUserDtoList = res.data.projectUsers.map(item => {
            return {
              ...item,
              showName: item.createName,
              leaderName: this.$options.filters.leaderFlagFilter(item.leaderFlag),
              postName: item.jobs
            }
          })
          let projectInitiationTaskList = Object.values(res.data.collect).map(item => {
            return item.map(ele => {
              let executorName = getType(ele.executorName).isArray ? ele.executorName.toString() : ele.executorName;
              return {
                ...ele,
                taskDate: [ele.startTime ? ele.startTime : '', ele.completionTime ? ele.completionTime : ''],
                executor: ele.executor && ele.executor.split(','),
                executorName: executorName,
                stageName: '标段' + this.$options.filters.chineseNumFilter(ele.stageNumber - 1),
                taskName: ele.task
              }
            })
          })
          console.log(1356, projectInitiationTaskList);
          this.$set(this.ruleForm, 'projectInitiationTaskList', projectInitiationTaskList);
          console.log('处理后的详情', this.ruleForm.approver);
          this.businessChange(false);
          // this.loadUserWidgetData()
          // this.loadTaskWidgetData()
          // this.loadPlanWidgetData()
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 项目成员列表
     */
    loadUserWidgetData () {
      let params = {
        projectId: this.$route.query.projectId
      };
      return new Promise((resolve, reject) => {
        Administration.userall(this, params).then(res => {
          this.ruleForm.projectUserDtoList = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 项目任务列表
     */
    loadTaskWidgetData () {
      let params = {
        projectId: this.$route.query.projectId
      };
      return new Promise((resolve, reject) => {
        Administration.tasklist(this, params).then(res => {
          let listData = res.data
          listData.forEach(item => {
            item.taskId = item.id
          })
          this.ruleForm.projectInitiationTaskList = listData
          this.$forceUpdate()
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 项目计划列表
     */
    loadPlanWidgetData () {
      let params = {
        projectId: this.$route.query.projectId
      };
      return new Promise((resolve, reject) => {
        Administration.planlist(this, params).then(res => {
          let listData = res.data
          listData.forEach(item => {
            item.taskIds = []
            item.planTaskVos.forEach(items => {
              item.taskIds.push(items.taskId)
            })
            let obj = {
              title: item.planName, // 事件内容
              start: item.beginDate, // 事件开始时间
              end: item.endDate, // 事件结束时间
              taskIds: item.taskIds,
              index: this.events.length,
              editable: false, // 事件是否可编辑
              color: '#409EFF' // 事件的显示颜色
            }
            this.events.push(obj)
          })
          this.ruleForm.projectPlanDtoList = listData
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 客户列表
     */
    loadCustomerList () {
      let params = ''
      return new Promise((resolve, reject) => {
        Customers.lists(this, params).then(res => {
          this.customerlist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 业务类型信息表树形列表
     */
    loadbusinesstypeTree () {
      return new Promise((resolve, reject) => {
        Businesstype.tree(this).then(res => {
          this.businesstypeTree = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    businessChange (isEditor) {
      console.log('选择业务类型', this.ruleForm.businessType);
      if (!this.ruleForm.businessType?.length) {
        this.ruleForm.projectInitiationTaskList = [];
        this.businessCode = '';
        return false;
      }
      this.ruleForm.projectAttribute = '';
      if (this.$refs['ref_business'].getCheckedNodes) {
        this.$nextTick(() => {
          let checkedNodes = this.$refs['ref_business'].getCheckedNodes()
          this.ruleForm.businessTypeParentIds = checkedNodes.map(item => item.path[0])
          this.businessCode = checkedNodes.some(item => item?.data?.businessCode === 'ZB') ? 'ZB' : '';
          // this.businessCode = checkedNodes[0].data.businessCode
          this.stageFlag = checkedNodes[0].data.stageFlag
          this.cooperateFlag = checkedNodes[0].data.cooperateFlag
          if (!isEditor) {
            return false;
          }
          this.loadDefautByBusinessType().then(() => {
            if (this.ruleForm.stageNumber) {
              this.selectStageNumber();
            }
          });
        });
      }
      this.$refs['ref_business'].dropDownVisible = false
    },
    deletetaskTemplate () {
      let projectInitiationTaskList = []
      this.ruleForm.projectInitiationTaskList.forEach((list, index) => {
        if (!projectInitiationTaskList[index]) {
          projectInitiationTaskList[index] = [];
        }
        list.forEach(item => {
          if (!item.taskTemplateId) {
            projectInitiationTaskList[index].push(item)
          }
        });
      });
      this.ruleForm.projectInitiationTaskList = projectInitiationTaskList
      this.loadDefautByBusinessType()
    },
    /**
     * 默认任务列表
     */
    loadDefautByBusinessType () {
      let params = {
        businessType: this.ruleForm.businessType.toString()
      }
      return new Promise((resolve, reject) => {
        Tasktemplate.templete(this, params).then(res => {
          this.ruleForm.projectInitiationTaskList = [];
          let listData = res.data
          listData.forEach((list, index) => {
            if (!list.length) {
              return false;
            }
            let arr = [];
            list.forEach(item => {
              let Obj = Object.assign({}, item, {
                executeUserId: '',
                endDate: '',
                userIds: '',
                taskTemplateId: item.id,
                defalutTaskFlag: 1,
                taskStatus: 1,
                task: item.taskName
              });
              arr.push(Obj);
              // if (!this.ruleForm.projectInitiationTaskList[index]) {
              //   this.$set(this.ruleForm.projectInitiationTaskList, index, []);
              // }
              // if (this.ruleForm.projectInitiationTaskList[index]?.length === 0) {
              //   Obj.taskId = this.fristTaskId
              // } else {
              //   let length = this.ruleForm.projectInitiationTaskList[index]?.length
              //   length = length - 1
              //   Obj.taskId = Number(this.ruleForm.projectInitiationTaskList[index][length].taskId) + 1
              // }
              // this.ruleForm.projectInitiationTaskList[index].push(Obj);
            });
            this.ruleForm.projectInitiationTaskList.push(arr);
            this.ruleForm.originalTaskList = Object.assign([], this.ruleForm.projectInitiationTaskList);
          })
          resolve();
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 行政区划
     */
    loadareaCodelistDict () {
      return new Promise((resolve, reject) => {
        EcologicalkKnowledge.listDict(this).then(res => {
          let areaCodelist = res.data
          let areaCodelistnew = []
          areaCodelist.forEach((item, index) => {
            if (!item.parentId) {
              item.children = []
              areaCodelistnew.push(item)
            }
          })
          areaCodelistnew.forEach((item1, index1) => {
            let info = areaCodelist.find((item2, index2) => {
              return item1.id === item2.parentId
            })
            if (info) {
              item1.children = []
              areaCodelist.forEach((item3, index3) => {
                if (item1.id === item3.parentId) {
                  item1.children.push(item3)
                }
              })
            } else {
              item1.children = null
            }
          })
          areaCodelistnew.forEach((item4, index4) => {
            if (item4.children) {
              item4.children.forEach((item5, index5) => {
                let info2 = areaCodelist.find((item6, index6) => {
                  return item5.id === item6.parentId
                })
                if (info2) {
                  item5.children = []
                  areaCodelist.forEach((item7, index7) => {
                    if (item5.id === item7.parentId) {
                      item5.children.push(item7)
                    }
                  })
                } else {
                  item5.children = null
                }
              })
            }
          })
          this.areaCodelist = areaCodelistnew
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 选择行政区划
     */
    areaCodesChange () {
      this.$refs['ref_areaCodes'].dropDownVisible = false
    },
    /**
     * 新增成员
     */
    setPeople (row) {
      // notSubmit
      if (row && row.notSubmit) {
        this.$message.warning('负责人不可编辑');
        return false;
      }
      this.selectPeoplebox = true
      localStorage.setItem('projectUserDtoList', JSON.stringify(this.ruleForm.projectUserDtoList))
      this.$nextTick(() => {
        this.$refs.selectPeople.info(this.ruleForm.projectUserDtoList)
      })
    },
    getPeople (data) {
      if (data.length !== 0) {
        this.ruleForm.projectUserDtoList = []
        this.ruleForm.projectUserDtoList = [...data]
      } else {
        this.ruleForm.projectUserDtoList = JSON.parse(localStorage.getItem('projectUserDtoList'))
        localStorage.setItem('projectUserDtoList', '')
      }
    },
    /**
     * 设置角色
     */
    setroles (data, index) {
      this.tableIndex = index
      this.setRolebox = true
      this.$nextTick(() => {
        this.$refs.setRole.info()
      })
    },
    getRole (data) {
      let tableIndex = this.tableIndex
      let projectUserDtoList = this.ruleForm.projectUserDtoList[tableIndex]
      projectUserDtoList.projectRoleName = data.projectRoleName
      this.$set(this.ruleForm.projectUserDtoList, tableIndex, projectUserDtoList)
    },
    // 删除成员
    deleteUserDtoList (row, index) {
      if (row && row.notSubmit) {
        this.$message.warning('负责人不可删除');
        return false;
      }
      this.ruleForm.projectUserDtoList.splice(index, 1)
    },
    /**
     * 创建任务
     */
    setTasks (index) {
      let data = {
        TaskType: 'add',
        examine: 1
      }
      let params = {
        projectPlanDtoList: this.ruleForm.projectPlanDtoList,
        projectUserDtoList: this.ruleForm.projectUserDtoList,
        businessType: this.ruleForm.businessType,
        detailInfo: data
      };
      let projectUserDtoList = this.ruleForm.projectUserDtoList
      this.$dialog.show('新建任务1', TasksAdd, {
        area: ['800px', '70vh']
      }, params).then(res => {
        console.log(res, projectUserDtoList, '新建任务333333');
        this.ruleForm.projectInitiationTaskList[index].push({
          ...res,
          executorName: projectUserDtoList.filter(item => res.executor.findIndex(ele => ele === item.userId) >= 0).map(item => item.showName)?.toString(),
          executorId: res.executor,
          mu: res.executor.map(item => {
            return {
              userId: item
            }
          }),
          taskName: res.task,
          taskStatus: 1, // 新增任务默认任务状态为进行中1,2为已完成
          // executor: res.executor.toString(), // 执行人Id集合
          // executorName: res.executorName.toString(), // 执行人名称集合
          businessStage: this.ruleForm.projectInitiationTaskList[index][0].businessStage,
          businessType: this.ruleForm.projectInitiationTaskList[index][0].businessType,
          businessTypeCode: this.ruleForm.projectInitiationTaskList[index][0].businessTypeCode,
          businessTypeName: this.ruleForm.projectInitiationTaskList[index][0].businessTypeName,
          stageNumber: this.ruleForm.projectInitiationTaskList[index][0].stageNumber,
          stageName: this.ruleForm.projectInitiationTaskList[index][0].stageName
        });
        console.log(this.ruleForm.projectInitiationTaskList[index], 8888)
      }).catch(e => {
      });
    },

    getTasks () {
      let TasksAddData = JSON.parse(localStorage.getItem('TasksAddData'))
      if (this.ruleForm.projectInitiationTaskList.length === 0) {
        TasksAddData.taskId = this.fristTaskId
      } else {
        let length = this.ruleForm.projectInitiationTaskList.length
        length = length - 1
        TasksAddData.taskId = Number(this.ruleForm.projectInitiationTaskList[length].taskId) + 1
      }
      TasksAddData.defalutTaskFlag = 0
      TasksAddData.taskTemplateId = null
      this.ruleForm.projectInitiationTaskList.push(TasksAddData)
      localStorage.setItem('TasksAddData', '')
      this.$forceUpdate()
    },
    // 编辑任务详情
    getTasksupdata (scope, index) {
      let data = {
        ...scope.row,
        TaskType: 'edit'
        // examine: 1
      };
      let i = scope.$index;
      console.log('编辑，打印data', data);
      // localStorage.setItem('projectInitiationTaskList', JSON.stringify(this.ruleForm.projectInitiationTaskList))
      let params = {
        projectPlanDtoList: this.ruleForm.projectPlanDtoList,
        projectUserDtoList: this.ruleForm.projectUserDtoList,
        businessType: this.ruleForm.businessType,
        taskTemplateId: data.taskTemplateId,
        detailInfo: data,
        typeId: '4'
      };
      let projectUserDtoList = this.ruleForm.projectUserDtoList
      if (data.taskId === data.id) {
        params.tasksId = data.taskId
      }
      this.$dialog.show('编辑任务', TasksAdd, {
        area: ['800px', '70vh']
      }, params).then(res => {
        console.log('编辑任务确定', res);
        this.$set(this.ruleForm.projectInitiationTaskList[index], i, {
          ...res,
          executorName: projectUserDtoList.filter(item => res.executor.findIndex(ele => ele === item.userId) >= 0).map(item => item.showName)?.toString(),
          executorId: res.executor,
          mu: res.executor.map(item => {
            return {
              userId: item
            }
          })
        });
      }).catch(e => {
        // this.ruleForm.projectInitiationTaskList = JSON.parse(localStorage.getItem('projectInitiationTaskList'))
        // localStorage.setItem('projectInitiationTaskList', '')
      });
    },
    // 删除任务
    deleteTask (scope, index) {
      let data = scope.row;
      let i = scope.$index;
      if (data.achievementFlag) {
        this.$message({
          showClose: true,
          message: '核心任务不能删除',
          center: true,
          type: 'warning'
        });
        return false;
      }
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$delete(this.ruleForm.projectInitiationTaskList[index], i);
      })
    },
    /**
     * 创建计划
     */
    setPlans () {
      let projectInitiationTaskList = this.ruleForm.projectInitiationTaskList
      this.setPlanbox = true
      this.$nextTick(() => {
        this.$refs.setPlan.info(projectInitiationTaskList)
      })
    },
    getPlans (data) {
      let PlanAddData = data
      this.ruleForm.projectPlanDtoList.push(PlanAddData)
      let obj = {
        title: data.planName, // 事件内容
        start: data.beginDate, // 事件开始时间
        end: data.endDate, // 事件结束时间
        taskIds: data.taskIds,
        index: this.events.length,
        editable: false, // 事件是否可编辑
        color: '#409EFF' // 事件的显示颜色
      }
      this.events.push(obj)
    },
    // 编辑计划
    eventClick (calEvent, jsEvent, view) {
      this.indexPlans = calEvent.index
      let projectInitiationTaskList = this.ruleForm.projectInitiationTaskList
      this.setPlanbox = true
      this.$nextTick(() => {
        this.$refs.setPlan.frominfo(projectInitiationTaskList, this.ruleForm.projectPlanDtoList[this.indexPlans])
      })
    },
    // 更新计划
    upPlans (data) {
      this.events = []
      this.ruleForm.projectPlanDtoList[this.indexPlans] = data
      this.ruleForm.projectPlanDtoList.forEach((item, index) => {
        let obj = {
          title: item.planName, // 事件内容
          start: item.beginDate, // 事件开始时间
          end: item.endDate, // 事件结束时间
          taskIds: item.taskIds,
          index: index,
          editable: false, // 事件是否可编辑
          color: '#409EFF' // 事件的显示颜色
        }
        this.events.push(obj)
      })
      this.$forceUpdate()
    },
    changePlans (data) {
      this.events = []
      this.ruleForm.projectPlanDtoList.splice(this.indexPlans, 1)
      this.ruleForm.projectPlanDtoList.forEach((item, index) => {
        let obj = {
          title: item.planName, // 事件内容
          start: item.beginDate, // 事件开始时间
          end: item.endDate, // 事件结束时间
          taskIds: item.taskIds,
          index: index,
          editable: false, // 事件是否可编辑
          color: '#409EFF' // 事件的显示颜色
        }
        this.events.push(obj)
      })
      this.$forceUpdate()
    },
    /**
     * 所属部门选中值改变
     */
    onDeptIdValueChange (value) {
      this.ruleForm.deptId = Array.isArray(value) ? value[value.length - 1] : undefined;
      this.loadDeptPost();
    },
    /**
     * 提交表单
     */
    submitForm () {
      console.log('this.ruleForm', this.ruleForm.cc);
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          if (this.$route.query.projectId) { // 项目编辑
            this.ruleForm.projectId = this.$route.query.projectId
            let params = {
              projectAddDto: {
                ...this.ruleForm,
                businessType: this.ruleForm.businessType.toString(),
                businessTypeParentIds: this.ruleForm.businessTypeParentIds.toString(),
                filePath: this.ruleForm.fileList,
                cc: this.ruleForm.cc?.map(item => item.userId)?.toString()
              }
            };
            return new Promise((resolve, reject) => {
              Administration.update(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '修改成功！',
                  type: 'success'
                });
                this.resetForm();
              }).catch(e => {
                reject(e);
              });
            });
          } else { // 项目立项
            let params = {
              projectAddDto: {
                ...this.ruleForm,
                businessType: this.ruleForm.businessType.toString(),
                businessTypeParentIds: this.ruleForm.businessTypeParentIds.toString(),
                filePath: this.ruleForm.fileList,
                cc: this.ruleForm.cc?.map(item => item.userId)?.toString()
              }
            };
            console.log(params)
            return new Promise((resolve, reject) => {
              Administration.add(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '添加成功！',
                  type: 'success'
                });
                this.resetForm();
              }).catch(e => {
                reject(e);
              });
            });
          }
        } else {
          return false;
        }
      });
    },
    resetForm () {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
h3 {
  border-bottom: 1px solid #e9e9eb;
  padding: 0 0 10px;
}
.require::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.table_container {
  margin: 10px 0;
}
.form-single-info {
  display: flex;
  justify-content: center;
}
.el-form-info {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}
.el-form-info strong {
  margin: 0 10px;
}
.el-form-info .el-time-picker {
  width: 100%;
}
.title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  h4 {
    font-weight: bold;
  }
}
.Taskslist {
  box-shadow: 0px 0px 7px 0px rgba(77, 165, 255, 0.3);
  border-radius: 0px 0px 4px 4px;
  padding: 10px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 10px 0;
  h4 {
    padding: 0;
    margin: 10px 0;
    font-weight: bold;
  }
  span {
    display: block;
    color: #409eff;
    margin: 10px 0;
  }
  .color-text1 {
    color: #f56c6c;
  }
  .color-text2 {
    color: #c0c4cc;
  }
  .listimg {
    width: 60px;
    height: 60px;
    border-radius: 100%;
    overflow: hidden;
  }
  .listimg .el-image {
    width: 100%;
    height: 100%;
  }
}
</style>
